package cn.org.itool.ws.framework.ws.command.po;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.util.Assert;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * 参考spring mvc handlerMethod
 * 限制如下： 方法只能有包含一个参数或者没有参数
 */
public class HandlerMethod {

    /**
     * 方法所属类的实例
     */
    private final Object serviceInstance;


    private final BeanFactory beanFactory;


    private final String beanName;

    /**
     * 处理方法
     */
    private final Method method;

    /**
     * 方法参数， 如果方法没有参数为 null.
     */
    private final Parameter[] methodArg;




    public HandlerMethod(BeanFactory beanFactory, String beanName, Method method, Parameter[] methodArg) {
        this.beanFactory = beanFactory;
        this.beanName = beanName;
        this.method = method;
        this.methodArg = methodArg;
        this.serviceInstance = null;
    }

    public HandlerMethod createWithResolvedBean() {
        Assert.state(this.beanFactory != null, "Cannot resolve bean name without BeanFactory");
        Object serviceInstance = this.beanFactory.getBean(beanName);
        return new HandlerMethod(this, serviceInstance);
    }

    private HandlerMethod(HandlerMethod handlerMethod, Object serviceInstance) {
        Assert.notNull(handlerMethod, "HandlerMethod is required");
        Assert.notNull(serviceInstance, "service bean is required");
        this.serviceInstance = serviceInstance;
        this.beanFactory = handlerMethod.beanFactory;
        this.beanName = handlerMethod.beanName;
        this.method = handlerMethod.method;
        this.methodArg = handlerMethod.methodArg;
    }

    public Object getServiceInstance() {
        return serviceInstance;
    }

    public Method getMethod() {
        return method;
    }

    public Parameter[] getMethodArg() {
        return methodArg;
    }
}
